package com.wanmait.happyheating.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.wanmait.happyheating.pojo.Admin;

import java.util.Calendar;
import java.util.Date;
/*
张晓峰 2021 05 20
 */
public class AdminJWTUtils
{

    public static String createToken(Admin admin) {

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,30);
        Date expiresDate = nowTime.getTime();


        return JWT.create().withAudience(admin.getId().toString())   //签发对象
                .withIssuedAt(new Date())
                .withExpiresAt(expiresDate)  //有效时间
                .withClaim("adminId",admin.getId())
                .withClaim("username", admin.getName())
                .withClaim("name", admin.getName())
                .sign(Algorithm.HMAC256(admin.getPass()));
    }

    public static void verifyToken(String token, String secret)
    {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            //效验失败
            throw new JWTVerificationException("token校验失败，非法认证信息");
        }

    }

    public static String getAudience(String token) {
        String audience=null;

        try {
            audience = JWT.decode(token).getAudience().get(0);

        } catch (JWTDecodeException j) {
            //这里是token解析失败
            throw new RuntimeException("token解析失败，非法认证信息");
        }
        return audience;
    }


    //通过载荷名字获取载荷的值
    public static Claim getClaimByName(String token, String name){
        return JWT.decode(token).getClaim(name);
    }
}
